package xiaojian.toolkit.redis;

import java.lang.reflect.Proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.util.ClassUtils;

import com.google.common.base.Preconditions;

public class Jedis2ProxyFactoryBean extends AbstractFactoryBean<Jedis2Commands> {
	
	private static final Logger logger = LoggerFactory.getLogger(Jedis2ProxyFactoryBean.class);

	private Jedis2Pool writeJedisPool;

	private Jedis2Pool readJedisPool;

	public Jedis2ProxyFactoryBean(Jedis2Pool writeJedisPool, Jedis2Pool readJedisPool) {
		Preconditions.checkArgument(writeJedisPool != null);
		
		this.writeJedisPool = writeJedisPool;
		if (readJedisPool != null) {
			this.readJedisPool = readJedisPool;
		} else {
			this.readJedisPool = writeJedisPool;
			logger.warn("Readable redis server is null, use writeable redis server instead.");
		}
	}

	

	public Class<Jedis2Commands> getObjectType() {
		return Jedis2Commands.class;
	}

	protected Jedis2Commands createInstance() throws Exception {
		PoolInvocationHandler handler = new PoolInvocationHandler(
				writeJedisPool, readJedisPool);
		return (Jedis2Commands) Proxy.newProxyInstance(
				ClassUtils.getDefaultClassLoader(),
				new Class[] { Jedis2Commands.class }, handler);
	}

}
